var mail = require('nodemailer');
var db = require('../database/mongo_database.js');
var fs = require('fs');
var crypt = require('./mycrypt.js');
var path = require('path');

var sendmail = function (user_id, indate, next) {
    
    db.users.findOne({ id: user_id }, function (error, success) {
        
        if (success) {
            
            console.log('正在发送编号为' + user_id + ',日期为 ' + indate + '的员工邮件');
            
            db.excels.findOne({ 'user_id': user_id, 'sent': '0', 'date': indate }, function (err, ok) {
                
                if (ok) {
                    try {
                        
                        var excelfile = ok.filepath;

                        console.log("已找到Excel文件路径 ->", excelfile);
                        
                        var transporter = mail.createTransport({
                            service: 'QQ',
                            auth: {
                                user: success.mail,
                                pass: crypt.decode(success.mailpwd, 'tsdykjhz')
                            }
                        });
                        
                        var mailoptions = {
                            from: { name: success.name, address: success.mail },
                            to: success.mail2+', ' + success.mail,
                            subject: success.name + ' ' + path.basename(excelfile),
                            html: '<b> 达意科技工作日志 by ' + success.name + "</b>",
                            attachments: [{ filename: path.basename(excelfile), path: excelfile }]
                        }
                        
                        transporter.sendMail(mailoptions, function (error, info) {
                            if (error) {
                                console.log(error);
                                return next(error);
                            } else {
                                //更新数据库
                                ok.sent = "1"
                                db.excels.save(ok);
                                console.log('邮件发送成功: ' + info.response);
                                return next(info);
                            }
                        });
                    
                    } catch (e) {
                        console.log(e);
                    }
                } else {
                    console.log(err);
                    return next(err);
                }
              
            });
        } else { console.log("ERR: ", err); }

       
    });
}


exports.sendmail = sendmail;